package com.chujian.file.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.chujian.framework.core.base.TsDataController;
import com.chujian.framework.core.tsdata.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author ：chujian
 * @date ：2020-12-09
 * 通用对象存储控制器
 */
@RestController
@Slf4j
public class FileController extends TsDataController {

    @Value("${chujian.file.localPath}")
    private String localPath;

    /**
     * 通用文件上传
     *
     * @param type    路径
     * @param request
     * @return
     */
    @PostMapping("/local/upload")
    public Result upload(
            @RequestParam("type") String type,
            HttpServletRequest request
    ) {
        List<String> urls = new ArrayList<>();
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                assert file != null;
                // 获取文件名
                String fileName = file.getOriginalFilename();
                String path = getFileName(type, fileName);
                byte[] bytes = IoUtil.readBytes(file.getInputStream());
                FileUtil.writeBytes(bytes, path);

                urls.add(path);
                log.info(" 文件:" + fileName + " 上传成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return errRs("上传失败");
        }
        return okRs(CollUtil.join(urls, ","));
    }

    /**
     * 获取本次保存的文件名
     *
     * @param type        文件类型
     * @param oriFileName 源文件名称
     */
    private String getFileName(String type, String oriFileName) {
        String filePath = localPath + new SimpleDateFormat("yyyyMM") + "/";
        File file = new File(filePath);
        if (!file.exists()) {
            boolean f = file.mkdirs();
        }
        String suffix = FileUtil.getSuffix(oriFileName);
        return filePath + IdUtil.fastSimpleUUID() + "." + suffix;
    }


}
